<template>
    <section v-loading="loading" element-loading-text="加载中..." element-loading-background="rgba(122, 122, 122, 0.2)"
        style="min-height:600px">

        <section>
            <el-scrollbar height="450px" always>
                <section class="contact-detail-wrapper">
                    <section v-for="m of groupMemberList" class="request-friends-list" :key="m.id">
                        <section v-if="m.roleId === 3" style="position:relative">
                            <img class="group-member-avatar" :src="m.userAvatar" @error="defaultAvatar" alt="">
                            <p class="group-member-nickname">{{ m.userNickname }}</p>
                            <p class="group-main">{{ m.roleName }}</p>
                        </section>

                        <el-dropdown @command="handleCommand($event, m)" size="small" trigger="click">
                            <section style="position:relative">
                                <template v-if="m.roleId !== 3">
                                    <img class="group-member-avatar" :src="m.userAvatar" @error="defaultAvatar" alt="">
                                    <p class="group-member-nickname" style="margin-top:4px">{{ m.userNickname }}</p>
                                    <p class="group-main manager-tag" v-if="m.roleId === 2">{{ m.roleName }}</p>
                                </template>
                            </section>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item command="remove"
                                        v-if="(isManage && m.userId != chatState.getUserInfo()?.id) || isGroupMain">移除该成员</el-dropdown-item>
                                    <el-dropdown-item command="manage"
                                        v-if="isGroupMain && m.roleId === 1">设为群管理员</el-dropdown-item>
                                    <el-dropdown-item command="exit"
                                        v-if="!isGroupMain && m.userId == chatState.getUserInfo()?.id">退出该群</el-dropdown-item>
                                    <el-dropdown-item command="ordinary"
                                        v-if="isGroupMain && m.roleId === 2">设为普通成员</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </section>
                </section>
            </el-scrollbar>

        </section>

        <section class="group-opration" v-show="chatState.currentChatName">
            <el-button type="primary" :icon="ChatRound" @click="sendGroupMessage">发消息</el-button>&nbsp;
            <el-button type="primary" :icon="Document" @click="historyMessage">历史聊天记录</el-button>&nbsp;
            <el-button type="primary" @click="dialogVisible = true" v-if="isManage || isGroupMain">+
                添加成员</el-button>&nbsp;
            <el-button type="danger" @click="editGroup" v-if="isGroupMain">群修改</el-button>
            <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" :icon="InfoFilled" icon-color="#626AEF"
                title="解散该群" @confirm="removeComfirm">
                <template #reference>
                    <el-button type="danger" v-if="isGroupMain">解散该群</el-button>
                </template>
            </el-popconfirm>

        </section>

        <el-dialog style="padding: 20px !important;" v-model="dialogVisible" title="备注信息" align-center center
            append-to-body width="500px" :before-close="handleClose">
            <section style="width: 100%;">
                <h2 style="margin-bottom: 30px;">可添加的群成员列表</h2>
                <section>
                    <section>
                        <el-scrollbar height="300px">
                            <template v-for="u of chatState.contacts" :key="u.id">
                                <section class="result-item">
                                    <ContactItem :userDetail="u" />
                                    <el-button type="primary" size="small" @click="addMember(u)">添加</el-button>
                                </section>
                            </template>
                        </el-scrollbar>
                    </section>
                </section>
            </section>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="dialogVisible = false">取消</el-button>
                </span>
            </template>
        </el-dialog>

        <el-dialog style="padding: 20px !important; " v-model="historyVisible" title="查看聊天记录" width="800px"
            :before-close="handleClose">
            <section style="width: 100%;">
                <h2>查看聊天记录</h2>
                <section class="infinite-list" style="overflow: auto; height: 400px;">
                    <DynamicScroller class="output-content-container" :min-item-size="54" :item-size="140"
                        :items="items" @scroll-end="scrollEnd">
                        <template v-slot="{ item, index, active }">
                            <DynamicScrollerItem :size="50" :active="active">
                                <HistoryChatItem :messageData="item" :key="index"
                                    :user-id="chatState.getUserInfo()?.id" />
                            </DynamicScrollerItem>
                        </template>
                    </DynamicScroller>
                </section>
            </section>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="historyVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmHandle" v-show="previewStatus == 'remove'">确认</el-button>
                </span>
            </template>
        </el-dialog>

        <el-dialog style="padding: 20px !important; " v-model="editGroupVisible" title="修改群信息" width="800px"
            :before-close="handleClose">
            <section style="width: 100%;">
                <h2 style="text-align: center;font-weight:500;font-size: 18px;">修改群信息</h2>
                <section style="width: 100%;">
                    <p>群名称：</p>
                    <el-input v-model="groupName" style="width: 100%; margin-top: 15px;"
                        placeholder="请输入群名称"></el-input>
                    <p style="margin-top: 20px">群头像：</p>
                    <section>
                        <avatar-edit-qun :value="groupAvatar" @update-Avatar="newAvatar" />
                        <!-- <el-upload v-model:file-list="fileList" ref="uploadFileAvatar" :on-change="uploadChange"
                            action="#" list-type="picture-card" :auto-upload="false" :limit="1">
                            <el-icon>
                                <Plus />
                            </el-icon>
                            <template #file="{ file }">
                                <div style="width: 100%;">
                                    <img class="el-upload-list__item-thumbnail" style="width: 200px;height: auto;"
                                        :src="file.url" alt="" />
                                    <span class="el-upload-list__item-actions">
                                        <span class="el-upload-list__item-preview"
                                            @click="handlePictureCardPreview(file)">
                                            <el-icon><zoom-in /></el-icon>
                                        </span>
                                        <span v-if="!disabled" class="el-upload-list__item-delete"
                                            @click="handleRemove(file)">
                                            <el-icon>
                                                <Delete />
                                            </el-icon>
                                        </span>
                                    </span>
                                </div>
                            </template>
                        </el-upload> -->
                    </section>
                    <p style="margin-top: 20px">群介绍：</p>
                    <el-input v-model="groupIntroduce" style="width: 100%; margin-top: 15px;"
                        placeholder="请输入群介绍"></el-input>
                </section>
            </section>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editGroupVisible = false">取消</el-button>
                    <el-button type="primary" @click="editGroupConfirm">确认</el-button>
                </span>
            </template>
        </el-dialog>

    </section>
</template>

<script setup>
import { ChatMessage } from '@/stores/chat'
import { defaultAvatar, formatTime } from '@/utils'
import { ChatRound, Document, Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue"
import { ElNotification } from 'element-plus'
import { DynamicScroller, } from "vue-virtual-scroller"
import "vue-virtual-scroller/dist/vue-virtual-scroller.css"
import HistoryChatItem from "./HistoryChatItem.vue"

// import type { UploadFile } from 'element-plus'

const uploadFileAvatar = ref()
const page = ref(1)
const limit = ref(10)
const chatMessageTotal = ref(0)
const chatState = ChatMessage()
const historyVisible = ref(false)
const dialogVisible = ref(false)
const previewStatus = ref('remove')

const groupMemberList = ref([])
const loading = ref(false)
const isGroupMain = ref(false)
const isManage = ref(false)
const editGroupVisible = ref(false)
const groupName = ref('')
const groupAvatar = ref('')
const groupIntroduce = ref('')
const dialogImageUrl = ref('')

const state = reactive({
    file: null,
    groupAvatar: '',
    groupInfo: {}
})

const props = defineProps({
    previewData: {
        type: Object,
        default: () => ({})
    }
})
const fileList = ref([{
    "name": "512.png",
    "percentage": 0,
    "status": "ready",
    "size": 76115,
    "raw": {
        "uid": 1729737032862
    },
    "uid": 1729737032862,
    "url": "http://117.34.99.190:8083/images/2024/10/24/084501691c98841640b6accb696a94bd.jfif"
}])
const list = ref([])
const userId = ref(0)

onMounted(() => {
    userId.value = chatState.getUserInfo()?.id || ''
})

const newAvatar = (msg) => {
    console.log(msg);
    groupAvatar.value = msg
    console.log(groupAvatar.value);
};

const items = computed(() => {
    return list.value.map((item, index) =>
        Object.assign({}, { id: `data-id-${index}` }, item),
    );
});

const handleClose = () => {
    dialogVisible.value = false
}

watch(() => historyVisible.value, (nVal) => {
    if (!nVal) {
        list.value = []
        page.value = 1
        chatMessageTotal.value = 0
    }
})

watch(() => props.previewData, (n, o) => {
    if (n.friendsType === 'groupChat') {
        groupMemberList.value = []
        getMember()
    }
}, {
    deep: true
})

const sendGroupMessage = () => {
    chatState.changeTagStatus('chat')
    chatState.setChatType(2)
    chatState.addChatList({
        lastMessage: '',
        friendId: props.previewData.groupId,
        time: formatTime(new Date(), 'HH:mm',),
        ready: true,
        value: 0,
        chatType: 2,
        ...props.previewData
    })
    chatState.updateCurrentMessageList()
}

const handleRemove = (file) => {
    uploadFileAvatar.value.handleRemove(file)
}

const handlePictureCardPreview = (file) => {
    dialogImageUrl.value = file.url
}

const uploadChange = (file) => {
    state.file = file.raw
}

const editGroup = async () => {
    let { name = '', introduce = '', avatar = '' } = await useMyFetch(`/api/chat-groups/${props.previewData.groupId}`);
    if (name) {
        groupIntroduce.value = introduce
        groupAvatar.value = avatar
        groupName.value = name
        editGroupVisible.value = true
    } else {
        ElNotification({
            title: '提示', message: '获取群信息失败， 请重试！',
            type: 'error',
        })
    }
}

const editGroupConfirm = async () => {
    if (groupName.value == '') {
        ElNotification({
            title: '提示', message: '群名称不能为空',
            type: 'warning',
        })
        return
    }
    // if (state.file.name) {
    //     const formData = new FormData();
    //     formData.append("image", state.file, state.file.name);
    //     let { url = '' } = await useHttpPostMultipart("/api/upload", formData).catch(err => {
    //         ElNotification({
    //             title: '提示',
    //             message: err.message || '文件上传失败, 请重试！',
    //             type: 'error',
    //         })
    //     })

    //     console.log(url);
    //     if (url) {
    //         state.groupAvatar = url
    //     }
    // }
    let res = await useMyFetchPostMultipart('/api/chat-groups/update', {
        body: {
            id: props.previewData.groupId,
            avatar: groupAvatar.value,
            name: groupName.value,
            introduce: groupIntroduce.value
        }
    }).catch(err => {
        ElNotification({
            title: '提示',
            message: err.message || '创建失败, 请重试！',
            type: 'error',
        })
    })
    if (res.result) {
        state.file = {}
        groupAvatar.value = ''
        editGroupVisible.value = false
        chatState.getGroupList()
    }
    console.log(res);

}

const getMember = async () => {
    isGroupMain.value = false
    isManage.value = false
    loading.value = true
    let { results = [] } = await useHttpGet(`/api/chat-groups/members/list?groupId=${props.previewData.groupId}`)
    groupMemberList.value = results || []
    loading.value = false
    if (groupMemberList.value?.length) {
        groupMemberList.value.forEach(item => {
            if (item.userId === chatState.getUserInfo()?.id && item.roleId === 3) {
                isGroupMain.value = true
                // isManage.value = true
            } else if (item.roleId === 2 && item.userId === chatState.getUserInfo()?.id) {
                isManage.value = true
            }
        })
    }
}

const removeComfirm = async () => {
    let res = await useMyFetchDeleteMultipart("/api/chat-groups/dissolve", {
        body: {
            groupId: props.previewData.groupId
        }
    })
    if (res.result) {
        groupMemberList.value = []
        chatState.setCurrentChatName('')
        chatState.getGroupList()
        chatState.removeCurrentChat(props.previewData.groupId)
        chatState.removeCurrentChatMessage(props.previewData.groupId)
        ElNotification({ title: '提示', message: '解散成功', type: 'success' })
    } else {
        ElNotification({ title: '提示', message: '解散失败', type: 'error' })
    }
}

const handleCommand = async (type, e) => {
    if (type === 'remove') {
        let res = await useMyFetchPostMultipart("/api/chat-groups/remove", {
            body: {
                groupId: props.previewData.groupId,
                memberId: e.userId
            }
        }).catch(err => {
            ElNotification({ title: '提示', message: err.message || '移除失败', type: 'error' })
        })
        if (res.result) {
            getMember()
            ElNotification({ title: '提示', message: '移除成功', type: 'success' })
        }
    } else if (type === 'manage') {
        setMemberRole(e.userId, 2)
    } else if (type === 'ordinary') {
        setMemberRole(e.userId, 1)
    } else if (type === 'exit') {
        ElMessageBox.confirm(
            '确定退出该群?',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'info',
                center: true,
            }
        ).then(async () => {
            let res = await useMyFetchDeleteMultipart("/api/chat-groups/exit", {
                body: {
                    groupId: props.previewData.groupId,
                }
            }).catch(err => {
                ElNotification({ title: '提示', message: err.message || '操作失败', type: 'error' })
            })
            if (res.result) {
                groupMemberList.value = []
                chatState.getGroupList()
                chatState.setCurrentChatName('')
                chatState.removeCurrentChat(props.previewData.groupId)
                chatState.removeCurrentChatMessage(props.previewData.groupId)
                ElNotification({ title: '提示', message: '已退出该群', type: 'success' })
            }
        }).catch(() => {
            ElMessage({
                type: 'info',
                message: '取消',
            })
        })

    }
}

const setMemberRole = async (memberId, role) => {
    let res = await useMyFetchPUTMultipart("/api/chat-groups/role", {
        body: {
            groupId: props.previewData.groupId,
            memberId,
            memberRoleId: role
        }
    }).catch(err => {
        ElNotification({ title: '提示', message: err.message || '设置失败', type: 'error' })
    })
    if (res.result) {
        getMember()
        ElNotification({ title: '提示', message: '设置成功', type: 'success' })
    }
}

const addMember = async (f) => {
    let res = await useMyFetchPostMultipart("/api/chat-groups/invite", {
        body: {
            groupId: props.previewData.groupId,
            friendId: f.friendId
        }
    }).catch(err => {
        ElNotification({ title: '提示', message: '添加失败, 请重试！', type: 'error', })
    })
    if (res.result) {
        ElNotification({ title: '提示', message: '添加成功', type: 'success' })
        getMember()
        dialogVisible.value = false
    }

}

const scrollEnd = (e) => {
    page.value++
    getHistoryMessageList()
}

const historyMessage = async () => {
    previewStatus.value = 'history'
    historyVisible.value = true
    getHistoryMessageList()
}

const getHistoryMessageList = async () => {
    if (list.value.length > 0 && (list.value.length == chatMessageTotal.value)) {
        return
    }
    let { results = [], page: { total = 0 }, message = '' } = await useHttpGet(`/api/chat-groups/record`, {
        params: {
            page: page.value,
            limit: limit.value,
            groupId: props.previewData.groupId
        }
    }).catch(err => {
        ElNotification({ title: '提示', message: err.message || '请求失败, 请重试！', type: 'error', })
    })
    chatMessageTotal.value = total
    if (results.length) {
        results = results.map(item => ({ ...item, time: formatTime(new Date(item.createdAt), 'YYYY-MM-DD HH:mm') }))
        list.value = [...list.value, ...results]
    }
}

</script>

<style scoped lang="scss">
.contact-detail-wrapper {
    display: flex;
    flex-direction: row;
    flex: 1;
    width: 100%;
    align-items: center;
    flex-wrap: wrap;
    padding: 20px 10px;
}

.result-item {
    display: flex;
    align-items: center;
    padding: 10px 0;
}

.output-content-container {
    height: 400px;
}

.group-opration {
    padding: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.request-friends-list {
    padding: 10px;
    display: flex;
    align-items: center;
    flex-direction: column;
    cursor: pointer;
    margin: 0 10px;

    .group-member-avatar {
        min-height: 40px;
        height: 40px;
        width: 40px;
        object-fit: cover;
    }

    .group-member-nickname {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        width: 40px;
        text-align: center;
        color: #a8a8a8;
    }

    &:hover {
        background-color: #e6e6e6;
    }

    .group-main {
        position: absolute;
        right: -10px;
        top: -10px;
        padding: 2px 5px;
        background: #296218;
        border-radius: 8px;
        // width: 35px;
        font-size: 12px;
        font-weight: normal;
        color: #fff;
    }

    .manager-tag {
        background: #E6A23C;
    }
}
</style>